package com.yupi.springbootinit.mq.mqttproxy;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Component
public class MqttProxyRunner implements CommandLineRunner {

    @Override
    public void run(String... args) {
        // 使用异步线程启动，不阻塞主程序
        ExecutorService executor = Executors.newSingleThreadExecutor(r -> {
            Thread t = new Thread(r, "mqtt-proxy-starter");
            t.setDaemon(true);  // 守护线程，主程序退出时自动结束
            return t;
        });

        executor.submit(this::startAllProxies);

        log.info("MQTT Proxy 启动任务已提交（异步执行，不阻塞主程序）");
    }

    private void startAllProxies() {
        List<String> printerIds = Arrays.asList(
                "M300-6",
                "M450H-1200-7",
                "M450H-1200-8"
        );

        for (String printerId : printerIds) {
            startProxyWithRetry(printerId, 3);
        }
    }

    private void startProxyWithRetry(String printerId, int maxRetries) {
        for (int attempt = 1; attempt <= maxRetries; attempt++) {
            try {
                log.info("正在启动 MQTT Proxy: {} (第{}次尝试)", printerId, attempt);

                MqttProxyService proxy = new MqttProxyService(
                        "tcp://10.10.65.66:1883",
                        printerId,
                        "v1.1"
                );
                proxy.start();

                log.info("✅ MQTT Proxy 已启动: {}", printerId);
                return;

            } catch (Exception e) {
                log.error("❌ MQTT Proxy 启动失败: {} (第{}次)", printerId, attempt, e);

                if (attempt < maxRetries) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                }
            }
        }
        log.error("MQTT Proxy 启动彻底失败: {}，已达最大重试次数", printerId);
    }
}